package com.example.tossednfound;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.*;

public class CreateEntryActivity extends Activity {
	public static int entryType; // 0 = lost item, 1 = found item, 2 = donation
	Button entry_enterButton, entry_cancelButton, entry_imageButton;
	EditText entry_itemName,  entry_address,
	entry_state, entry_zipcode, entry_country, entry_description,
	entry_date, entry_rewardAmount, entry_tags;
	TextView header, entry_location;
	Spinner spinner_category;
	
	private int year;
	private int month;
	private int day;
	static final int DATE_DIALOG_ID = 999;
	private static final int CAMERA_PIC_REQUEST = 1337;


	//DatePicker entry_date;
	//private static String datePickerDate;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create_entry);
		entry_itemName = (EditText) findViewById(R.id.entry_item_name);
		entry_date = (EditText) findViewById(R.id.entry_item_date);
		entry_location = (TextView) findViewById(R.id.entry_item_location);
		entry_address = (EditText) findViewById(R.id.entry_item_address);
		entry_state = (EditText) findViewById(R.id.entry_item_state);
		entry_zipcode = (EditText) findViewById(R.id.entry_item_zipcode);
		entry_country = (EditText) findViewById(R.id.entry_item_country);
		entry_description = (EditText) findViewById(R.id.entry_item_description);
		entry_rewardAmount = (EditText) findViewById(R.id.entry_rewardAmount);
		entry_enterButton = (Button) findViewById(R.id.entry_item_enterbutton);
		entry_cancelButton = (Button) findViewById(R.id.entry_item_cancelbutton);
		entry_imageButton = (Button) findViewById(R.id.entry_imageButton);
		spinner_category = (Spinner) findViewById(R.id.entry_categorySpinner);
		entry_tags = (EditText) findViewById(R.id.entry_item_tags);
		header = (TextView) findViewById(R.id.header_text);

		if(entryType == 0) { // Found
			header.setText("What did you find?");
			entry_location.setText("Location Found:");
			entry_rewardAmount.setVisibility(View.GONE);
		}
		else if(entryType == 1) { // Lost
			header.setText("What did you lose?");
		}
		else if(entryType == 2) { // Donation
			header.setText("What are you donating?");
			entry_rewardAmount.setVisibility(View.GONE);
			entry_enterButton.setText("Donate!");

		}

		addCategoriesToSpinner();
		final Calendar c = Calendar.getInstance();
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH);
		day = c.get(Calendar.DAY_OF_MONTH);

		entry_date.setText(new StringBuilder()
		.append(month + 1).append("-").append(day).append("-")
		.append(year).append(" "));

		entry_date.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if(hasFocus){
					getDate();
				}
			}
		});

		findViewById(R.id.entry_item_enterbutton).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						makeEntry();
					}
				});

		findViewById(R.id.entry_item_cancelbutton).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						onBackPressed();
					}
				});
		findViewById(R.id.entry_imageButton).setOnClickListener(
				new View.OnClickListener() {
					public void onClick(View view) {
						Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
						startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
					}
				});
	}
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
	    if (requestCode == CAMERA_PIC_REQUEST) {  
	          
	    	Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
	    	ImageView image =(ImageView) findViewById(R.id.imageView);
	    	image.setImageBitmap(thumbnail);
	    } else {
	    	Toast.makeText(CreateEntryActivity.this, "Picture Not taken", Toast.LENGTH_LONG).show();
	    	
	    }
	    super.onActivityResult(requestCode, resultCode, data);
	}
	 
		

	/**
	 * makes entries
	 */
	public void makeEntry() {
		
		String category = String.valueOf(spinner_category.getSelectedItem());
		String itemName = entry_itemName.getText().toString();
		String date = new StringBuilder().append(month + 1)
				.append("-").append(day).append("-").append(year)
				.append(" ").toString();
		String location = entry_location.getText().toString();
		String address = entry_address.getText().toString();
		String state = entry_state.getText().toString();
		String zipcode = entry_zipcode.getText().toString();
		String country = entry_country.getText().toString();
		String description = entry_description.getText().toString();
		String tags = entry_tags.getText().toString();
		int reward = Integer.parseInt(entry_rewardAmount.getText().toString());

		Item entry;
		try {
			if(entryType == 0) { // found
				entry = new Item(LoginActivity.loggedIn.name, "null", reward,
						category, location, tags, date,
						itemName, entryType, description, state, zipcode, address, country);
			}
			else if( entryType == 1) { // lost
				entry = new Item(LoginActivity.loggedIn.name, "null", reward,
						category, location, "tags", date,
						itemName, entryType, description, state, zipcode, address, country);
			}
			else { //donation
				entry = new Item(LoginActivity.loggedIn.name, "null", reward,
						category, location, "tags", date,
						itemName, entryType, description, state, zipcode, address, country);
			}
			LoginActivity.ItemList.add(entry);
			LoginActivity.currentItem = entry;
			Dialog d = new Dialog(this);
			if(entryType != 2) {
				d.setTitle("Item Successfully Created!");
				TextView tv = new TextView(this);
				tv.setText(LoginActivity.currentItem.toString());
				d.setContentView(tv);
			}
			else {
				d.setTitle("Thank you!");
				TextView tv = new TextView(this);
				tv.setText("You're Awesome!");
				d.setContentView(tv);
			}

			d.show();
			Intent itemListViewActivity = new Intent(
					"android.intent.action.ITEMLISTVIEWACTIVITY");
			startActivity(itemListViewActivity);
		}
		catch (Exception e) {
			Dialog d = new Dialog(this);
			d.setTitle("Error: Item not created");
			TextView tv = new TextView(this);
			tv.setText("Please try recreating the item with all fields filled out");
			d.setContentView(tv);
			d.show();
		}

	}

	public static class DatePickerFragment extends DialogFragment implements
	DatePickerDialog.OnDateSetListener {

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Use the current date as the default date in the picker
			final Calendar c = Calendar.getInstance();
			int year = c.get(Calendar.YEAR);
			int month = c.get(Calendar.MONTH);
			int day = c.get(Calendar.DAY_OF_MONTH);

			// Create a new instance of DatePickerDialog and return it
			return new DatePickerDialog(getActivity(), this, year, month, day);
		}

		public void onDateSet(DatePicker view, int year, int month, int day) {
			//datePickerDate = day + "-" + month + "-" + year;
		}

		public void showDatePickerDialog(View v) {
			DialogFragment newFragment = new DatePickerFragment();
			newFragment.show(getFragmentManager(), "datePicker");
		}
	}
	/**
	 * adds categories to the spinner for categories
	 */
	public void addCategoriesToSpinner() {

		List<String> list = new ArrayList<String>();
		list.add("Keepsake");
		list.add("Heirloom");
		list.add("Miscellaneous");
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, list);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner_category.setAdapter(dataAdapter);
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		Intent regHomeActivity = new Intent(
				"android.intent.action.REGHOMEACTIVITY");
		startActivity(regHomeActivity);
	}
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, datePickerListener, 
					year, month,day);
		}
		return null;
	}
	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

		// when dialog box is closed, below method will be called.
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			year = selectedYear;
			month = selectedMonth;
			day = selectedDay;

			// set selected date into textview
			entry_date.setText(new StringBuilder().append(month + 1)
					.append("-").append(day).append("-").append(year)
					.append(" "));

		}
	};
	@SuppressWarnings("deprecation")
	private void getDate(){
		showDialog(DATE_DIALOG_ID);
	}
}
